package apis

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/config"
	"github.com/google/uuid"
	"gorm.io/gorm"
	"net/http"
	"time"
	"tuowei.com/app/api/models"
	"tuowei.com/app/api/service"
	"tuowei.com/app/api/service/dto"
	"tuowei.com/pkg/xlog"
)

const appId, appSecret = "wxf741b8a76b5eed4f", "e10171fa13551455f3fb68b746e80001"

type ApiWxLogin struct {
	api.Api
}

func (e ApiWxLogin) AuthLogin(ctx *gin.Context) {
	req := dto.WxLoginReq{}
	studentService := service.ApiStudent{}
	err := e.MakeContext(ctx).MakeOrm().MakeService(&studentService.Service).Bind(&req, binding.JSON).Errors
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	obj := new(models.SysWxStudent)
	stuObj := new(models.SysStudent)
	err = e.Orm.Where("openid = ?", req.OpenId).First(obj).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			// 未找到
			//插入
			err = e.Orm.Transaction(func(tx *gorm.DB) error {
				// 生成student
				stuObj.IsRegistered = 1
				stuObj.NickName = req.NickName
				stuObj.Cover = req.AvatarUrl
				stuObj.Status = 1
				err = tx.Create(stuObj).Error
				if err != nil {
					return err
				}
				// 生成wechat
				req.Generate(obj)
				obj.StudentId = stuObj.Id
				err = tx.Create(obj).Error
				if err != nil {
					return err
				}
				return nil

			})
			if err != nil {
				e.Error(http.StatusInternalServerError, err, err.Error())
				return
			}

		} else {
			e.Error(http.StatusInternalServerError, err, err.Error())
			return
		}
	} else {
		// 已经有此账号了，直接查询出当前student信息
		err = e.Orm.Where("id = ?", obj.StudentId).First(stuObj).Error
		if err != nil {
			e.Error(http.StatusInternalServerError, err, err.Error())
			return
		}
	}
	// 检测学员购买状态
	// 结业状态不让登陆
	if stuObj.BuyStatus == 3 {
		e.Error(http.StatusInternalServerError, nil, err.Error())
		return
	}
	uid := uuid.NewString()
	e.Orm.Table(models.SysStudent{}.TableName()).Where("id = ?", stuObj.Id).Update("logined", uid)
	// 登陆，返回授权token
	err = studentService.GerStudentInfo(stuObj, stuObj.Id)
	if err != nil {
		e.Error(http.StatusInternalServerError, err, err.Error())
		return
	}
	claim := StudentClaims{
		Student:        stuObj,
		StandardClaims: jwt.StandardClaims{},
	}
	now := time.Now()
	claim.StandardClaims.IssuedAt = now.Unix()
	claim.StandardClaims.ExpiresAt = now.Add(time.Duration(config.JwtConfig.Timeout) * time.Second).Unix()
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
	tokenStr, err := token.SignedString([]byte(config.JwtConfig.Secret))
	if err != nil {
		xlog.Error(http.StatusInternalServerError, err, err.Error())
		return
	}

	e.Context.JSON(http.StatusOK, gin.H{
		"code":          http.StatusOK,
		"is_registered": stuObj.IsRegistered,
		"expire":        now.Add(time.Duration(config.JwtConfig.Timeout) * time.Second),
		"token":         tokenStr,
	})
	return

}
